<template>
  <div>
    <el-dialog
      :visible="showEditDialog"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="true"
      :class="{'mobile-el-dialog-form global-mobile-dialog': showMobilePage}"
      class="large-common-dialog-size create-settle-dialog"
      @closed="handleClose"
    >
      <div class="info-box">
        <div v-if="hasRouteAuth('crm:customer:clientInfo:read')">
          <Title title="基本信息" style="margin-bottom:12px" font-size="16px"/>
          <el-form ref="contactRef" :rules="rules" :model="formData" :class="{'mobile-el-form': showMobilePage}" :label-position="showMobilePage?'left':'right'" label-width="86px" class="info-form" >
            <el-row type="flex" class="response-el-row">
              <el-col :span="8">
                <el-form-item label="客户类型" prop="clientType">
                  <el-select v-model="formData.clientType" :disabled="!hasRouteAuth('crm:customer:typeEdit')" size="small" popper-class="global-select-down" class="width240" name="clientType">
                    <el-option
                      v-for="item in clientList"
                      :key="item.id"
                      :label="item.value"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" prop="clientName">
                  <div class="flex-center relative">
                    <el-input
                      v-model.trim="formData.clientName"
                      :disabled="canEdit"
                      :maxlength="50"
                      size="small"
                      name="clientName"
                      style="flex: 1;"
                      placeholder="请输入客户的全称"
                      type="text"
                      @change="changeClientName" />
                    <el-input v-if="clientRepeatAuth && formData.clientType" v-model.trim="dupNameCode" :disabled="canEdit" placeholder="重名识别号" size="small" maxlength="20" style="width: 95px; margin-left: 8px;" />
                    <el-button v-if="clientRepeatAuth === 2" size="small" type="primary" style="padding: 7px 3px;margin-left: 4px;" @click="toCreateApproval(formData.clientName)">
                      <div class="flex-center">
                        申请协作
                        <tipIcon class="ml5" content="已存在相同名称客户，无需新建客户，请申请协作权限"/>
                      </div>
                    </el-button>
                    <div v-if="clientRepeatAuth && formData.clientType && !dupNameCode" class="footer-tip">客户名称重复，请输入识别号（建议手机尾号后4位）</div>
                    <div v-if="clientRepeatAuth && !formData.clientType && clientRepeatAuth === 1" class="footer-tip">已拥有该客户的权限，请勿重复创建</div>
                    <InfoIcon :content="canEdit ? '要修改客户名称请联系财务经理' : '请填写客户的真实全称'" style="width: 14px;height: 14px;margin-left: 4px;" />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户状态" prop="clientStatus">
                  <el-select v-model="formData.clientStatus" size="small" popper-class="global-select-down" class="width240" name="clientStatus">
                    <el-option
                      v-for="item in clientStatusList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户来源">
                  <el-input v-model="formData.clientSource" :maxlength="50" size="small" name="clientSource" class="width240" type="text" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户行业">
                  <el-input v-model="formData.clientBusiness" :maxlength="50" size="small" name="clientBusiness" class="width240" type="text" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属集团">
                  <template slot="label">
                    <span style="display: inline-flex;align-items: center;white-space: nowrap;">所属集团
                      <InfoIcon content="输入客户名称超过6个字时才可匹配集团名称" style="width: 16px;height: 16px;margin-left: 4px;" />
                    </span>
                  </template>
                  <el-select
                    ref="groupSelectRef"
                    v-model="formData.groupId"
                    :remote-method="getGroupList"
                    size="small"
                    popper-class="global-select-down"
                    name="groupId"
                    multiple
                    collapse-tags
                    clearable
                    filterable
                    remote
                    class="width240"
                    @focus="groupFocus">
                    <el-option
                      v-for="item in groupList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标签">
                  <TagSelect v-model="formData.tag" :collapse-tags="false" :module-type="TAG_MODULES.SETTLE_CUSTOMER" class="width240" />
                </el-form-item>
              </el-col>
              <el-col :span="8" class="indentation-form-item">
                <el-form-item>
                  <template slot="label">
                    <span style="display: flex;align-items: center;">实际客户名称
                      <InfoIcon content="选择必填后，创建订单选择该客户时，实际客户名称需要必填" style="width: 14px;height: 14px;margin-left: 4px;min-width:14px;" />
                    </span>
                  </template>
                  <el-radio v-model="formData.actualClientRequired" :label="1">必填</el-radio>
                  <el-radio v-model="formData.actualClientRequired" :label="0">非必填</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注" class="remark">
                  <el-input v-model.trim="formData.remark" :maxlength="500" size="small" class="client-textarea width240" name="remark" type="text" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div v-show="hasRouteAuth('crm:customer:levelInfo:read')">
          <Title title="等级账期" style="margin:7px 0 12px" font-size="16px"/>
          <el-form ref="levelInfoFormRef" :rules="levelRules" :model="formData" :class="{'mobile-el-form': showMobilePage}" label-width="86px" class="form" label-position="right">
            <el-row type="flex" class="response-el-row">
              <el-col :span="8">
                <el-form-item label="客户等级" prop="clientGrade">
                  <div class="flex-center">
                    <el-select
                      v-model="formData.clientGrade"
                      size="small"
                      popper-class="global-select-down"
                      style="width: 100%"
                      class="width240">
                      <el-option
                        v-for="item in clientLevelOptions"
                        :key="item.name"
                        :label="item.name"
                        :value="item.name"
                        :disabled="!canSelectLevel(item)" />
                    </el-select>
                    <InfoIcon style="width: 14px;height: 14px;margin-left: 4px;" content="置灰显示的等级表示你无权限调整，若需设置可保存客户后发起申请" />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="indentation-form-item">
                <el-form-item label="欠款额度(元)">
                  <el-input v-model.trim="formData.oweAmount" disabled placeholder="选择客户等级后将自动填入" class="width240" size="small" type="text"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="欠款账期">
                  <el-input
                    v-model.trim="formData.accountPeriod"
                    disabled
                    type="number"
                    placeholder="选择客户等级后将自动填入"
                    size="small"
                    class="width240"
                    @mousewheel.native.prevent>
                    <i slot="suffix" style="position:relative;right:20px;color:#333">天</i>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div v-if="hasRouteAuth('crm:customer:invoiceInfo:read')">
          <Title title="开票信息" style="margin:7px 0 12px" font-size="16px"/>
          <el-form :model="formData" :class="{'mobile-el-form': showMobilePage}" label-width="86px" class="form" label-position="right">
            <el-row type="flex" class="response-el-row">
              <el-col :span="8" :class="formData.clientType?'':'indentation-form-item'">
                <el-form-item :label="formData.clientType?'身份证号':'纳税人识别号'">
                  <el-input :disabled="canEdit" v-model.trim="formData.invoiceInfo.taxpayerNum" :maxlength="20" class="width240" size="small" type="text" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开户行">
                  <el-input v-model.trim="formData.invoiceInfo.openBank" :maxlength="50" class="width240" size="small" type="text" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开户账号">
                  <el-input v-model.trim="formData.invoiceInfo.accountNum" :maxlength="50" class="width240" size="small" type="text" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="注册电话">
                  <el-input v-model.trim="formData.invoiceInfo.phone" :maxlength="50" class="width240" size="small" type="text" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开票地址">
                  <el-input v-model.trim="formData.invoiceInfo.invoiceAddress" :maxlength="50" class="width240" size="small" type="text" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="indentation-form-item">
                <el-form-item label="一般纳税人证明">
                  <upAttachment
                    ref="uploadAttachment"
                    :hide-confirm="true"
                    :file-list="formData.invoiceInfo.taxpayerAttachment"
                    import-api="/common/file/upload"
                    btn-text="上传文件"
                    class="width240"
                    @complateSetData="completeSetData($event, 'taxpayerAttachment')"
                    @removeFileList="removeFileList($event, 'taxpayerAttachment')"
                    @downloadSuccess="downloadSuccess" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="flex-center btns">
        <el-button class="ok submit-btn" type="primary" size="small" @click="handleSubmit">确定<i v-if="submitLoading" class="el-icon-loading"/></el-button>
        <el-button class="back-btn cancel-btn-style" size="small" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
    <CreateApproval ref="CreateApprovalRef" />
  </div>
</template>

<script>
import Title from '@/components/Title';
import TagSelect from '@/components/Common/tagSelect';
import upAttachment from '@/components/Common/upAttachment/index';
import CreateApproval from '../../cooperation/createApproval';
import { getClientGroup, getLevelList, editClient, repeatClientName } from '@/api/customer';
import { getClientStatus } from '@/api/select';
import { TAG_MODULES } from '@/utils/const';
import ElMessage from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';

export default {
  components: { Title, TagSelect, upAttachment, CreateApproval },
  data() {
    return {
      TAG_MODULES,
      showEditDialog: false,
      groupList: [],
      groupListCopy: [],
      rules: {
        clientType: [{ required: true, trigger: 'change', message: '请选择客户类型' }],
        clientName: [{ required: true, trigger: 'blur', message: '请输入客户的全称' }],
        clientStatus: [{ required: true, trigger: 'change', message: '请选择客户状态' }]
      },
      levelRules: {
        clientGrade: [{ required: true, trigger: 'change', message: '请选择客户等级' }]
      },
      clientList: [
        { id: 0, value: '公司' },
        { id: 1, value: '个人' }
      ],
      clientStatusList: [],
      submitLoading: false,
      clientLevelOptions: [],
      clientRepeatAuth: 0,
      dupNameCode: '',
      formData: {
        clientStatus: '',
        groupId: [],
        invoiceInfo: {}
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    }),
    canEdit() {
      return !this.hasRouteAuth('crm:customer:editClientName');
    }
  },
  watch: {
    'formData.clientGrade'(data) {
      data && this.$nextTick(() => {
        const value = typeof data === 'object' ? data.name : data;
        const targetList = this.clientLevelOptions.filter(i => i.name === value);
        const targetData = targetList[0] || {};
        this.formData.oweAmount = targetData.oweAmount;
        this.formData.accountPeriod = targetData.accountPeriod;
      });
    }
  },
  created() {
    this.clientStatusOption();
    this.getGroupData();
    this.queryLevelAndInfo();
  },
  methods: {
    hasRouteAuth,
    clientStatusOption() {
      getClientStatus().then((res) => {
        this.clientStatusList = res.data;
      });
    },
    async getGroupData() {
      const { data } = await getClientGroup();
      this.groupList = data;
      this.groupListCopy = data;
    },
    getGroupList(val) {
      const el = this.$refs.groupSelectRef.popperElm;
      if (val && val.length > 6) {
        el.style.visibility = 'visible';
        this.groupList = this.groupListCopy.filter(it => it.name.includes(val));
      } else {
        el.style.visibility = 'hidden';
      }
    },
    groupFocus(e) {
      const el = this.$refs.groupSelectRef.popperElm;
      if (!e.target.value || e.target.value.length < 7) {
        el.style.visibility = 'hidden';
      } else {
        el.style.visibility = 'visible';
      }
    },
    // 客户等级和详情
    async queryLevelAndInfo() {
      try {
        const levelInfoData = await getLevelList();
        this.clientLevelOptions = levelInfoData && levelInfoData.data || [];
      } catch (e) {
        console.log(e);
      }
    },
    // 等级有设置岗位且不包含当前用户岗位时，不可选
    canSelectLevel(data) {
      if (!data.post || (Array.isArray(data.post) && !data.post.length)) return true;
      return data.post.includes(this.userInfo.post);
    },
    async changeClientName(name) {
      try {
        const res = await repeatClientName({ clientName: name });
        if (res.code === 200 && res.data) {
          this.clientRepeatAuth = res.data.isRepeat;
          if (!this.clientRepeatAuth) {
            this.dupNameCode = '';
          }
        }
      } catch (error) {
        this.clientRepeatAuth = false;
      }
    },
    toCreateApproval(name) {
      this.$refs.CreateApprovalRef.openDialog(name);
    },
    openDialog(data) {
      if (data) {
        this.formData = JSON.parse(JSON.stringify(data));
        if (this.formData.group) {
          const temp = this.formData.group.map(item => item.id);
          this.$set(this.formData, 'groupId', temp);
        }
        this.dupNameFormat();
      }
      this.showEditDialog = true;
    },
    downloadSuccess(name) {
      this.$emit('downloadSuccess', { name });
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.formData.invoiceInfo[key]) {
        this.formData.invoiceInfo[key].push(fileList);
      } else {
        this.$set(this.formData.invoiceInfo, key, [fileList]);
      }
    },
    removeFileList({ file, index }, key) {
      this.formData.invoiceInfo[key].splice(index, 1);
    },
    handleSubmit: _.debounce(function() {
      try {
        const params = [];
        this.$refs['contactRef'] && params.push(this.$refs['contactRef'].validate());
        if (!hasRouteAuth('crm:customer:levelInfo:read')) { // 无权限，默认回填等级最低的客户等级
          if (this.clientLevelOptions.length) {
            this.formData.clientGrade = this.clientLevelOptions[this.clientLevelOptions.length - 1].name;
          } else {
            this.formData.clientGrade = '新客户';
          }
        } else {
          this.$refs['levelInfoFormRef'] && params.push(this.$refs['levelInfoFormRef'].validate());
        }
        Promise.all(params).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            const dupNameCodeCheck = this.clientRepeatAuth && this.formData.clientType ? !!this.dupNameCode : true;
            if (dupNameCodeCheck) {
              this.toSubmit();
            } else {
              ElMessage.warning('请填写重名识别号');
            }
          } else {
            return false;
          }
        }).catch((error) => {
          ElMessage.warning('请检查信息是否填写完整');
          console.log('error', error);
        });
      } catch (err) {
        console.log(err);
      }
    }, 500),
    toSubmit() {
      this.submitLoading = true;
      // 处理参数
      const params = JSON.parse(JSON.stringify(this.formData));
      params.contactObj = params.contactObj.map(item => {
        if (item.contactPerson) item.contactPerson = item.contactPerson.trim();
        if (item.associate) item.associate = item.associate.map(item => item.id);
        if (item.coDepartment) item.coDepartment = item.coDepartment.map(item => item.id);
        item.createTime = item.createTime === '--' ? null : item.createTime;
        delete item.department;
        return item;
      });
      if (this.dupNameCode && this.formData.clientType) {
        params.clientName += `(${this.dupNameCode})`;
      }
      params.tag = params.tag ? params.tag.map(item => {
        return item.id;
      }) : [];
      params.payers = params.payers.map(item => {
        if (item.associate) item.associate = item.associate.map(item => item.id);
        if (item.coDepartment) item.coDepartment = item.coDepartment.map(item => item.id);
        return item;
      });
      if (params.accountPeriod) params.accountPeriod = Number(params.accountPeriod);
      params.isDialogEdit = true;
      // 参数处理结束
      editClient(this.formData.id, params).then(({ code, message }) => {
        this.submitLoading = false;
        ElMessage.success('修改成功');
        this.handleClose();
        this.$emit('updateDetail');
      }, result => {
        this.submitLoading = false;
      });
    },
    dupNameFormat() {
      if (this.formData.clientName.includes('(')) {
        this.clientRepeatAuth = 1;
        const pattern = /([^(\s]+)\s*\(([^)]+)\)/;
        const result = this.formData.clientName.match(pattern);
        if (result) {
          this.formData.clientName = result[1];
          this.dupNameCode = result[2].replace(/[()]/g, '');
        }
      }
    },
    handleClose() {
      this.showEditDialog = false;
      this.$refs.contactRef && this.$refs.contactRef.resetFields();
      this.$refs.levelInfoFormRef && this.$refs.levelInfoFormRef.resetFields();
      this.formData = {
        clientStatus: '',
        groupId: [],
        invoiceInfo: {}
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.info-form {
  &::v-deep{
    .el-select {
      .el-tag {
        background-color: #eff3fb;
        color: #333;
        position: relative;
        &:first-of-type{
          padding-right: 20px;
        }
        .el-select__tags-text {
          display: inline-block;
          max-width: 120px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .el-tag__close {
          position: absolute;
          top: 4px;
          right: 0px;
          font-size: 16px;
          background-color: transparent;
          color: #333;
        }
      }
    }
    .el-radio {
      .el-radio__label {
        font-size: 14px;
      }
    }
  }
}
.width240 {
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
    .el-upload {
      width: 240px;
    }
  }
}
.indentation-form-item {
  ::v-deep .el-form-item {
    label {
      line-height: 1.2 !important;
    }
  }
}
.btns {
  justify-content: center;
}
.info-box {
  max-height: 70vh;
  overflow: auto;
}
.relative {
  position: relative;
}
.footer-tip {
  position: absolute;
  bottom: -20px;
  line-height: 20px;
  display: flex;
  font-size: 12px;
  color: #F56C6C;
  white-space: nowrap;
}
</style>
